package com.wyw.leetcode.learning.simple;

import com.wyw.leetcode.simple.parent.ListNode;

/**
 * leetcode topic 206
 * 反转链表
 *
 * @Author Mr Wu    yewen.wu.china@gmail.com
 * Update History:
 * Author        Time            Content
 */
public class Topic206 {

    public static void main(String[] args) {
        ListNode listNode1 = null;
        for(int i=7; i > 1; i--) {
            ListNode listNodeNew = new ListNode(2 * i);
            listNodeNew.next = listNode1;
            listNode1 = listNodeNew;
        }
//        ListNode listNode = reverseList(listNode1);
//        ListNode listNode = reverseList1(listNode1);
        ListNode listNode = reverseList3(listNode1);
        System.out.println("end");
    }

    /**
     * 迭代
     */
    public static ListNode reverseList1(ListNode head) {
        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }
        ListNode result = null;
        while (head != null) {
            if(result == null) {
                ListNode temp = new ListNode();
                temp.val = head.val;
                result = temp;
            } else {
                ListNode temp = new ListNode();
                temp.next = result;
                temp.val = head.val;
                result = temp;
            }
            head = head.next;
        }
        return result;
    }

    /**
     * 题解迭代
     */
    public static ListNode reverseList2(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    /**
     * 递归
     */
    public static ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }
        return recursionListNode(head, null);
    }

    public static ListNode recursionListNode(ListNode head, ListNode result) {
        ListNode newListNode = new ListNode(head.val);
        newListNode.next = result;
        if(head.next!=null) {
            newListNode = recursionListNode(head.next, newListNode);
        }
        return newListNode;

    }

    /**
     * 题解递归
     */
    public static ListNode reverseList3(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList3(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
